package com.sywb.chuangyebao.widget;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.NewsDetail;
import com.sywb.chuangyebao.bean.NewsOwner;
import com.sywb.chuangyebao.bean.NewsRecommend;
import com.sywb.chuangyebao.relation.ShowPicRelation;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.RegexUtils;
import com.sywb.chuangyebao.view.UserIndexActivity;

import org.bining.footstone.adapter.BaseRecyclerAdapter;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.adapter.listener.OnItemClickListener;
import org.bining.footstone.utils.SharedUtils;
import org.bining.footstone.utils.TimeUtils;
import org.bining.footstone.widget.TagsLayout;

import java.util.List;

/**
 * 新闻详情页头部
 */
public class NewsDetailHeaderView extends FrameLayout {

    private static final String NICK = "chuangyebao";

    public TextView tvTitle;
    public ImageView ivAvatar;
    public ImageView ivLabel;
    public TextView tvAuthor;
    public TextView tvTime;
    public TextView tvFollow;
    public WebView wvContent;
    public TagsLayout tlTags;
    public TextView tvPraise;
    public LinearLayout llProject;
    public ImageView ivProjectAvatar;
    public ImageView ivProjectLabel;
    public TextView tvProjectAuthor;
    public TextView tvProjectTag;
    public TextView tvProjectIntro;
    public LinearLayout tvProjectIndex;
    public LinearLayout tvProjectCall;
    public LinearLayout llRecommend;
    public RecyclerView rvRecommend;

    private Activity mActivity;

    private NewsDetailHeaderViewListener newsDetailHeaderViewListener;

    private RecommendAdapter recyclerAdapter;

    public NewsDetailHeaderView(Activity activity) {
        this(activity, null);
    }

    public NewsDetailHeaderView(Activity activity, AttributeSet attrs) {
        this(activity, attrs, 0);
    }

    public NewsDetailHeaderView(Activity activity, AttributeSet attrs, int defStyleAttr) {
        super(activity, attrs, defStyleAttr);

        inflate(activity, R.layout.layout_news_detail_header, this);

        // addView(view, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        mActivity = activity;

        tvTitle = findViewById(R.id.tvTitle);
        ivAvatar = findViewById(R.id.iv_avatar);
        ivLabel = findViewById(R.id.iv_label);
        tvAuthor = findViewById(R.id.tv_author);
        tvTime = findViewById(R.id.tv_time);
        tvFollow = findViewById(R.id.tv_follow);
        wvContent = findViewById(R.id.wv_content);
        tlTags = findViewById(R.id.tl_tags);
        tvPraise = findViewById(R.id.tv_praise);
        llProject = findViewById(R.id.ll_project);
        ivProjectAvatar = findViewById(R.id.iv_project_avatar);
        ivProjectLabel = findViewById(R.id.iv_project_label);
        tvProjectAuthor = findViewById(R.id.tv_project_author);
        tvProjectTag = findViewById(R.id.tv_project_tag);
        tvProjectIntro = findViewById(R.id.tv_project_intro);
        tvProjectIndex = findViewById(R.id.tv_project_index);
        tvProjectCall = findViewById(R.id.tv_project_call);
        llRecommend = findViewById(R.id.ll_recommend);
        rvRecommend = findViewById(R.id.rv_recommend);

    }

    public void setDetail(NewsDetail detail, final NewsDetailHeaderViewListener listener) {
        this.newsDetailHeaderViewListener = listener;

        tvTitle.setText(detail.title);
        tvTime.setText(TimeUtils.transformDate10(detail.publish_time));
        if (TextUtils.isEmpty(detail.content)) {
            wvContent.setVisibility(GONE);
        } else {
            wvContent.getSettings().setJavaScriptEnabled(true);//设置JS可用
            // wvContent.getSettings().setLoadWithOverviewMode(true);
            wvContent.addJavascriptInterface(new ShowPicRelation(mActivity), NICK);//绑定JS和Java的联系类，以及使用到的昵称

            String htmlPart1 = "<!DOCTYPE HTML html>\n" +
                    "<head><meta charset=\"utf-8\"/>\n" +
                    "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, user-scalable=no\"/>\n" +
                    "</head>\n" +
                    "<body>\n" +
                    "<style> \n" +
                    "img{width:100%!important;height:auto!important}\n" +
                    " </style>";
            String htmlPart2 = "</body></html>";

            // String html = htmlPart1 + detail.content + htmlPart2;
            String html = detail.content;

            wvContent.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
            wvContent.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    //super.onPageFinished(view, url);
                    addJs(view);//添加多JS代码，为图片绑定点击函数
                    if (newsDetailHeaderViewListener != null) {
                        newsDetailHeaderViewListener.onLoadFinished();
                    }
                }
            });
        }

        if (detail.count != null) {
            setIsThumb(detail.is_thumb, detail.count.thumb_up);
        } else {
            setIsThumb(detail.is_thumb, 0);
        }

        tvPraise.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (newsDetailHeaderViewListener != null) {
                    newsDetailHeaderViewListener.onPraiseClick();
                }
            }
        });

        NewsOwner newsOwner = detail.owner;
        if (newsOwner != null) {

            GlideUtils.getCircleImageToUrl(mActivity, newsOwner.getShowAvatar(), ivAvatar, R.drawable.head_image);

            tvAuthor.setText(newsOwner.getShowName());


            ivAvatar.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (listener != null) {
                        listener.onUserClick();
                    }
                }
            });

            tvAuthor.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (listener != null) {
                        listener.onUserClick();
                    }
                }
            });

            llProject.setVisibility(View.GONE);

            int userRole = newsOwner.getUserRole();
            if (userRole == Constants.USER_TYPE_NORMAL) {
                ivLabel.setVisibility(View.GONE);
            } else {
                ivLabel.setVisibility(View.VISIBLE);
                switch (userRole) {
                    case Constants.USER_TYPE_V:
                        ivLabel.setImageResource(R.drawable.official_icon);
                        break;
                    case Constants.USER_TYPE_PROJECT:
                        ivLabel.setImageResource(R.drawable.icon_project);

                        llProject.setVisibility(View.VISIBLE);

                        GlideUtils.getCircleImageToUrl(mActivity, newsOwner.getShowAvatar(), ivProjectAvatar, R.drawable.head_image);
                        tvProjectAuthor.setText(newsOwner.getShowName());
                        ivProjectLabel.setImageResource(R.drawable.icon_project);
                        tvProjectTag.setText("项目号");

                        tvProjectIntro.setText(newsOwner.brief_intro);

                        ivProjectAvatar.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (listener != null) {
                                    listener.onUserClick();
                                }
                            }
                        });

                        tvProjectAuthor.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (listener != null) {
                                    listener.onUserClick();
                                }
                            }
                        });

                        ivProjectLabel.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (listener != null) {
                                    listener.onUserClick();
                                }
                            }
                        });

                        ivProjectAvatar.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (listener != null) {
                                    listener.onUserClick();
                                }
                            }
                        });

                        tvProjectIndex.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (newsDetailHeaderViewListener != null) {
                                    newsDetailHeaderViewListener.onProjectIndexClick();
                                }
                            }
                        });

                        tvProjectCall.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (newsDetailHeaderViewListener != null) {
                                    newsDetailHeaderViewListener.onProjectCallClick();
                                }
                            }
                        });
                        break;
                    case Constants.USER_TYPE_SERVICE:
                        ivLabel.setImageResource(R.drawable.icon_service);
                        break;
                    case Constants.USER_TYPE_TUTOR:
                        ivLabel.setImageResource(R.drawable.icon_teacher);
                        break;
                }
            }

            boolean isLogin = SharedUtils.getBoolean(Constants.USERISLOGIN, false);
            String openId = SharedUtils.getString(Constants.USEROPENID, "");
            if (isLogin && openId.equals(String.valueOf(newsOwner.uid))) {
                tvFollow.setBackgroundResource(R.drawable.round_line_gray);
                tvFollow.setTextColor(ContextCompat.getColor(mActivity, R.color.colorGray));
                tvFollow.setText("关注");
                tvFollow.setClickable(false);
            } else {
                setIsFollow(newsOwner.is_follow);
            }
        } else {
            ivAvatar.setImageResource(R.drawable.head_image);
            tvAuthor.setText(detail.writer);
            ivLabel.setVisibility(View.GONE);
            tvFollow.setVisibility(View.GONE);
        }

        if (detail.tag != null && detail.tag.size() > 0) {
            tlTags.setVisibility(View.VISIBLE);
            tlTags.setData(detail.tag).show();
            tlTags.setOnItemClickListener(new TagsLayout.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int i) {
                    if (newsDetailHeaderViewListener != null) {
                        newsDetailHeaderViewListener.onTagsClick(i);
                    }
                }
            });
        } else {
            tlTags.setVisibility(View.GONE);
        }

        List<NewsRecommend> recommendList = detail.recommend;
        if (recommendList != null && recommendList.size() > 0) {
            llRecommend.setVisibility(View.VISIBLE);
            recyclerAdapter = new RecommendAdapter(mActivity);
            rvRecommend.setAdapter(recyclerAdapter);
            rvRecommend.setLayoutManager(new LinearLayoutManager(mActivity));
            recyclerAdapter.setDatas(recommendList);

            recyclerAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(View view, int i) {
                    if (newsDetailHeaderViewListener != null) {
                        newsDetailHeaderViewListener.onRecommenItemClick(recyclerAdapter.getDatas().get(i).article_id);
                    }
                }
            });
        } else {
            llRecommend.setVisibility(View.GONE);
        }
    }

    public void setWebviewFocusable() {
        wvContent.setFocusable(false);
    }

    public void setIsThumb(boolean isThumb, int thumbCount) {
        Drawable drawable;
        if (isThumb) {
            drawable = getResources().getDrawable(R.drawable.praise_fill);
        } else {
            drawable = getResources().getDrawable(R.drawable.praise);
        }
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tvPraise.setCompoundDrawables(drawable, null, null, null);
        tvPraise.setText(thumbCount > 0 ? RegexUtils.getFormatNum(thumbCount) : "点赞");
    }

    public void setIsFollow(boolean isFollow) {
        if (!isFollow) {
            tvFollow.setBackgroundResource(R.drawable.round_pie_msg_unread);
            tvFollow.setTextColor(ContextCompat.getColor(mActivity, R.color.colorLight));
            tvFollow.setText("+ 关注");
            tvFollow.setClickable(true);
            tvFollow.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (newsDetailHeaderViewListener != null) {
                        newsDetailHeaderViewListener.onFollowClick();
                    }
                }
            });
        } else {
            tvFollow.setBackgroundResource(R.drawable.round_line_gray);
            tvFollow.setTextColor(ContextCompat.getColor(mActivity, R.color.colorGray));
            tvFollow.setText("已关注");
            tvFollow.setClickable(false);
        }
    }

    /**
     * 添加JS代码，获取所有图片的链接以及为图片设置点击事件
     */
    private void addJs(WebView wv) {
        wv.loadUrl("javascript:(function  pic(){" +
                "var imgList = \"\";" +
                "var imgs = document.getElementsByTagName(\"img\");" +
                "for(var i=0;i<imgs.length;i++){" +
                "var img = imgs[i];" +
                "imgList = imgList + img.src +\";\";" +
                "img.onclick = function(){" +
                "window.chuangyebao.openImg(this.src);" +
                "}" +
                "}" +
                "window.chuangyebao.getImgArray(imgList);" +
                "})()");
    }

    public void setNewsDetailHeaderViewListener(NewsDetailHeaderViewListener newsDetailHeaderViewListener) {
        this.newsDetailHeaderViewListener = newsDetailHeaderViewListener;
    }

    /**
     * 页面加载的回调
     */
    public interface NewsDetailHeaderViewListener {
        void onLoadFinished();

        void onUserClick();

        void onFollowClick();

        void onProjectIndexClick();

        void onProjectCallClick();

        void onPraiseClick();

        void onTagsClick(int postion);

        void onRecommenItemClick(int articleId);
    }

    class RecommendAdapter extends BaseRecyclerAdapter<NewsRecommend> {

        public RecommendAdapter(Context context) {
            super(context, R.layout.item_news_detail_recommend);
        }

        @Override
        protected void setItemData(ViewHolderHelper viewHolderHelper, int i, NewsRecommend data) {
            viewHolderHelper.setText(R.id.tv_title, data.title);
        }
    }
}
